#if defined(_WIN32) || defined(WIN32) 
#define OS_WIN
#endif
#define DEFAULT_BUFLEN 512

#include <iostream>
#include <string>
using namespace std;
#include "Network.h"

void checkMsg(char *recvbuf);
#ifdef OS_WIN
//Windows specific stuff
#define OS 0
WinSockNetwork network;
#include <conio.h>

DWORD WINAPI ThreadFunc(void* data) {
	// Do stuff.  This will be the first funciton called on the new thread.
	int running=1;
	char recvbuf[DEFAULT_BUFLEN];
	while(running==1){

		int iResult=network.receiveMessage(recvbuf);
		if(iResult>0){
			checkMsg(recvbuf);
		}
	}

	// When this function returns, the thread goes away.  See MSDN for more details.
	return 0;
}

#else
//Mac related stuff
#define OS 1
BSDNetwork network;
#endif






void checkMsg(char *recvbuf){

	printf("Received this string from server:%s\nNow I plan to parse it into the game\n",recvbuf);
	char messageType;
	int len=strlen(recvbuf);
	/*string input(recvbuf,len);//info is the the message
	char *cstr=new char(input.size()+1);
	strcpy(cstr,input.c_str());
	*/
	char *token;
	token=strtok(recvbuf,"\n");
	//for each message in the recv

	while(token!=NULL){
		//string message
		string message(token);
		messageType=recvbuf[0];
		message=message.substr(2,len);

		printf("messageType:%c\n",messageType);
		cout<<"message:"<<message<<endl;
		if(recvbuf[0]=='0'){

		}
		token=strtok(NULL,"\n");
	}


}
int main ()
{
	char *sendbuf = "0 this is a test\n";

	cout << "OS is:"<<OS<<endl;
	network.sendMessage(sendbuf);
	//network.sendMessage("0 helloworld\n");



	//windows
#ifdef OS_WIN	
	HANDLE thread = CreateThread(NULL, 0, ThreadFunc, NULL, 0, NULL);
	//mac
#else
	//fork a new process to deal receive messages?
	if(!fork()){
		//child process, do the same as the windows thread
		int running=1;
		char recvbuf[DEFAULT_BUFLEN];
		while(running==1){
			int iResult=network.receiveMessage(recvbuf);
			if(iResult>0){
				checkMsg(recvbuf);
			}
		}
	}
	
#endif
	string mystr;
	char buf[256];
	while(true){
		cout<<"Enter something to send:";
		getline(cin,mystr);
		mystr.copy(buf,mystr.length());
		//cout<<"mystr.length:"<<mystr.length();
		buf[mystr.length()]='\0';
		buf[mystr.length()+1]='\n';
		network.sendMessage(buf);
	}
	return 0;
}

